package ru.compft.app.as_db.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import ru.compft.common.data.AppUser;
import ru.compft.common.services.UserService;
import ru.compft.web.beans.ErrorBean;
import ru.compft.web.beans.PasswordBean;

import javax.annotation.Resource;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * User: VVasiliev
 * Date: 14.06.12
 * Time: 13:43
 * Контроллер подсистемы Личного кабинета
 */
@Controller("personalController")
@RequestMapping("/personal")
@Scope("session")
public class PersonalController implements Serializable {
    private static final long serialVersionUID = -7107605390667245270L;

    private static final Logger logger = LoggerFactory.getLogger(PersonalController.class);

    private static final String DEFAULT_VIEW = "personal";

    @Resource(name = "userService")
    private UserService userService;

    @Resource(name = "сhangePasswordBeanValidator")
    private Validator validator;

    @Resource(name = "errorBean")
    private ErrorBean errorBean;

    @ModelAttribute(ErrorBean.BEAN_NAME)
    public ErrorBean getErrorBean() {
        return errorBean;
    }

    @ModelAttribute("passwBean")
    public PasswordBean getPasswordBean() {
        return new PasswordBean();
    }

    /**
     * Регистрируем конвертер дат
     * Формат дат - 2012-10-29 23:23:21.0
     */
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * Отображение страницы по умолчанию
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public String showDefaultPage() {
        System.out.println("Show default view");

        if (logger.isDebugEnabled()) {
            logger.debug("Show default view - " + DEFAULT_VIEW);
        }

        return DEFAULT_VIEW;
    }

    /**
     * Метод POST без параметров
     *
     * @param model
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public String defaultPost(Model model) {
        return showDefaultPage();
    }

    /**
     * Отображение страницы "Смена пароля"
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/changePassw", method = RequestMethod.GET)
    public String showChangePasswPage(Model model) {
        System.out.println("invoke showChangePasswPage method.");

        return "changePasswPage";
    }

    /**
     * Действие по кнопке "Отмена"
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/changePassw", method = RequestMethod.POST, params = {"cancel"})
    public String cancelChangePassw(Model model) {
        System.out.println("invoke cancelChangePassw method. ");

        return showDefaultPage();
    }

    /**
     * Действие по кнопке "Сохранить"
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/changePassw", method = RequestMethod.POST, params = {"save"})
    public String saveNewPassw(Model model,
                               @RequestParam("save") String save,
                               @ModelAttribute("passwBean") PasswordBean passwordBean,
                               BindingResult result) {
        System.out.println("invoke saveNewPassw method. save = " + save);

        // валидация
        validator.validate(passwordBean, result);

        // нет ошибок валидации - идем дальше
        // если пароли не идентичны - кинем ошибку
        if (!result.hasErrors()) {
            final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.isAuthenticated()) {
                final String login = (String) authentication.getPrincipal();

                final AppUser appUser = new AppUser();
                appUser.setLogin(login);

                final AppUser appUser1 = userService.changePassword(appUser, passwordBean.getPassword());
                System.out.println("SaveNewPassw was = " + (appUser1 != null));

                return showDefaultPage();
            }
        }

        return "changePasswPage";
    }
}
